package com.superlz.demo.security.web.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * spring拦截器（可获取对应方法和类的信息）
 *
 * 1.实现HandlerInterceptor的方法
 * 2.config中继承WebMvcConfigurerAdapter，重写addInterceptors方法
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

	/**
	 * 访问之前调用，返回false，不调用执行后面的方法
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("preHandle");
		
		System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
		System.out.println(((HandlerMethod)handler).getMethod().getName());

		// 设置属性传递
		request.setAttribute("startTime", System.currentTimeMillis());
		return true;
	}

	/**
	 * 访问之后调用（异常时，不被调用）
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		// 获取属性传递
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("time interceptor postHandle 耗时:"+ (System.currentTimeMillis() - start));

	}

	/**
	 * 访问之后调用（均被调用）
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("time interceptor afterCompletion 耗时:"+ (System.currentTimeMillis() - start));

		// 注意：该异常会被 ControllerExceptionHandler 进行拦截处理，此时该返回null
		System.out.println("ex is "+ex);

	}

}
